# -*- coding: utf-8 -*-
class OpeningStockController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter ,:except =>[:hxListForOpeningStock,:commonReport]
  after_filter :sys_after_log

  #为系统权限服务的空方法
  def openingStockList

  end

  #为系统权限服务的空方法
  def openingStockAuditList

  end

  #为系统权限服务的空方法
  def newOpeningStock

  end

  #显示编辑期订单的页面
  def editOpeningStock

  end

  #为系统权限服务的空方法
  def auditOpeningStock

  end

  def analysis

  end

  def getAllOpeningStocks
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i
      conditionsStr = ''

      if params[:order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'seq_number in (:order_number)'
        else
          conditionsStr = conditionsStr + ' AND seq_number in (:order_number)'
        end
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'vendor_id = :vendor_id'
        else
          conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
        end
        conditionsHash[:vendor_id] = params[:vendor_id].to_i
      end

      if params[:to_warehouse_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'warehouse_id = :warehouse_id'
        else
          conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
        end
        conditionsHash[:warehouse_id] = params[:to_warehouse_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      #产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'opening_stock_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND opening_stock_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end
      logger.info conditionsStr
      if session[:financial_management] == '是'
        selectStr = "description,audit_opinion,value_added_tax,tax_rate,is_locked,contract_number,warehouse_id,department_id,created_at,vendor_id,seq_number,linkman,deal_with_status,employee_id,updated_at,auditing_status,action_employee_id,lock_version,amount,tax_amount,id,action_date,order_number,phone,company_id,auditor_id"
      else
        selectStr = "description,audit_opinion,tax_rate,is_locked,contract_number,warehouse_id,department_id,created_at,vendor_id,seq_number,linkman,deal_with_status,employee_id,updated_at,auditing_status,action_employee_id,lock_version,id,action_date,order_number,phone,company_id,auditor_id"
      end

      role = Role.find(session[:role_id])
      if role.cross_company == "否"
        if conditionsStr == ''
          conditionsStr = 'company_id = :company_id'
        else
          conditionsStr = conditionsStr+' AND company_id = :company_id'
        end
        conditionsHash[:company_id] = session[:company_id]
      end

      count = OpeningStock.count(:all,:include=> [:opening_stock_details],:conditions => [conditionsStr,conditionsHash])
      openingStocks = OpeningStock.all(
        :select=>"#{selectStr}",
        :conditions => [conditionsStr,conditionsHash],
        :include=> [:employee,:department,:vendor,:auditor,:action_employee,:warehouse],
        :offset => paramsHash[:offset],
        :limit => paramsHash[:limit],
        :order => 'opening_stocks.updated_at DESC'
      )

      jsonStr="{totalProperty:"+count.to_s+",root:"+openingStocks.to_json(:include=>[:company,:employee,:department,:vendor,:auditor,:action_employee,:warehouse])+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #根据审批状态得到所有期初单据
  def getAllOpeningStocksByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      conditionsStr = conditionsStr + ' AND seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:vendor_id].to_s != ''
      conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
      conditionsHash[:vendor_id] = params[:vendor_id].to_i
    end

    if params[:to_warehouse_id].to_s != ''
      conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
      conditionsHash[:warehouse_id] = params[:to_warehouse_id].to_i
    end

    if params[:begin_date].to_s != ''
      conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      conditionsStr = conditionsStr+' AND action_date <= :end_date'
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    if session[:financial_management] == '是'
      selectStr = "value_added_tax,tax_rate,is_locked,contract_number,warehouse_id,department_id,created_at,vendor_id,seq_number,linkman,deal_with_status,employee_id,updated_at,auditing_status,action_employee_id,lock_version,amount,tax_amount,id,action_date,order_number,phone,company_id,auditor_id"
    else
      selectStr = "tax_rate,is_locked,contract_number,warehouse_id,department_id,created_at,vendor_id,seq_number,linkman,deal_with_status,employee_id,updated_at,auditing_status,action_employee_id,lock_version,id,action_date,order_number,phone,company_id,auditor_id"
    end
    count = OpeningStock.count(:all,:include=> [:opening_stock_details],:conditions => [conditionsStr,conditionsHash])
    openingStocks = OpeningStock.all(
      :select=>"#{selectStr}",
      :conditions => [conditionsStr,conditionsHash],
      :include=> [:opening_stock_details],
      :offset => paramsHash[:offset],
      :limit => paramsHash[:limit],
      :order => 'opening_stocks.updated_at DESC'
    )

    #jsonStr="{totalProperty:"+count.to_s+",root:"+openingStocks.to_json(:include=>[:employee,:department,:vendor,:auditor,:action_employee,:warehouse])+"}"
    jsonStr="{totalProperty:"+count.to_s+",root:"+openingStocks.to_json(:include=>{:employee=>{:only=>[:id,:name]},:department=>{:only=>[:id,:name]},:vendor=>{:only=>[:id,:name]},:auditor=>{:only=>[:id,:name]},:action_employee=>{:only=>[:id,:name]},:warehouse=>{:only=>[:id,:name]}})+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #创建新的期初单据
  def create
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    #productHash = paramsHash["products"][0]

    openingStock = OpeningStock.new
    openingStock.company_id = session[:company_id]
    openingStock.department_id = session[:department_id]
    openingStock.employee_id = session[:employee_id]
    openingStock.vendor_id = paramsHash['vendor_id']
    openingStock.warehouse_id = paramsHash['warehouse_id']
    openingStock.linkman = paramsHash['linkman']
    openingStock.phone = paramsHash['phone']
    openingStock.tax_rate = paramsHash['tax_rate']
    openingStock.action_date = paramsHash['action_date']
    openingStock.description = paramsHash['description']


    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash['temporary'] == '1'
      openingStock.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_opening_stock_add == "否"
        openingStock.auditing_status = Constants::PASS_APPLY_ADD
        openingStock.deal_with_status = ''
      else
        openingStock.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end

    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #只有当用户选择的产品不为空时，才有详细订单。
      if productHash["product_id"] !=""
        openingStockDetail = OpeningStockDetail.new
        openingStockDetail.product_id = productHash["product_id"]
        openingStockDetail.quantity = productHash["quantity"]
        openingStockDetail.unit_price = productHash["unit_price"]
        openingStockDetail.amount = productHash["amount"]
        openingStockDetail.tax_price = productHash["tax_price"]
        openingStockDetail.tax_amount = productHash["tax_amount"]
        openingStockDetail.value_added_tax = productHash["value_added_tax"]
        openingStock.amount = openingStock.amount + openingStockDetail.amount #计算订单总金额
        openingStock.tax_amount = openingStock.tax_amount + openingStockDetail.tax_amount #计算订单总金额(含税)
        openingStock.value_added_tax = openingStock.value_added_tax + openingStockDetail.value_added_tax #计算订单总金额(含税)
        openingStockDetail.description = productHash["description"]
        openingStock.opening_stock_details << openingStockDetail
      end
    end
    #openingStock.save

    #开始事务，确保在流水号正常的情况下，保存销售订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为销售订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],OpeningStock.name).first

        sequence.seq_no = sequence.seq_no + 1
        openingStock.seq_number = sequence.seq_no
        openingStock.order_number = sequence.ab + ":" + openingStock.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        openingStock.save!

        #如果不需要审批，则直接提交到汇总表
        #把数据一个个的插入到结算表中。
        if paramsHash['temporary'] != '1' && sysParam.audit_for_opening_stock_add == "否"
          openingStockDetails = openingStock.opening_stock_details
          openingStockDetails.each do |openingStockDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = openingStock.company_id
            productCollection.department_id = openingStock.department_id
            productCollection.employee_id = openingStock.employee_id
            productCollection.vendor_id = openingStock.vendor_id
            productCollection.warehouse_id = openingStock.warehouse_id
            productCollection.product_id = openingStockDetail.product_id
            productCollection.quantity =  openingStockDetail.quantity
            productCollection.amount = openingStockDetail.amount
            productCollection.tax_amount = openingStockDetail.tax_amount #计算订单总金额(含税)
            productCollection.value_added_tax = openingStockDetail.value_added_tax #税金
            productCollection.description =  openingStockDetail.description
            productCollection.action_date = openingStock.action_date
            productCollection.resource_id =  openingStock.id
            productCollection.resource_type =  OpeningStock.name
            productCollection.save!
          end
        end
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def update
    data = params[:data]

    begin
      paramsHash = Util.paramsPreprocessToHash(params[:data])
      
      openingStock = OpeningStock.where("id = ? AND company_id = ? AND is_locked <> 1 AND auditing_status <> ?",paramsHash['id'],session[:company_id],'通过').first
      if openingStock != nil
        if openingStock.lock_version > paramsHash['lock_version'].to_i
          info="有其它用户在您保存之前编辑过此期初订单记录，请从新编辑！"
          result = "{success:true,info:'#{info}'}"
          render :text=>result, :layout=>false and return false
        end

        openingStock.company_id = session[:company_id]
        openingStock.department_id = session[:department_id]
        openingStock.employee_id = session[:employee_id]
        openingStock.vendor_id = paramsHash['vendor_id']
        openingStock.linkman = paramsHash['linkman']
        openingStock.phone = paramsHash['phone']
        openingStock.contract_number = paramsHash['contract_number']
        openingStock.tax_rate = paramsHash['tax_rate']
        openingStock.action_date = paramsHash['action_date']
        openingStock.description = paramsHash['description']
        
        openingStock.audit_opinion = ''
        openingStock.auditor_id = ''

        #判断一下当前用户角色是否需求审批
        sysParam =  SysParam.find_by_company_id(session[:company_id])

        #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
        if paramsHash['temporary'] == '1'
          openingStock.deal_with_status = Constants::TEMP_ADD
        else
          if sysParam.audit_for_opening_stock_add == "否"
            if openingStock.auditing_status == Constants::AUDIT_APPLY_ADD
              openingStock.auditing_status = Constants::PASS_APPLY_ADD
            else
              openingStock.auditing_status = Constants::PASS_APPLY_EDIT
            end
            openingStock.deal_with_status = ''
          else
            if openingStock.auditing_status == Constants::AUDIT_APPLY_ADD
              openingStock.auditing_status = Constants::AUDIT_APPLY_ADD
            elsif
              openingStock.auditing_status = Constants::AUDIT_APPLY_EDIT
            end
          end
        end

        #products信息
        productsHashArray = paramsHash["products"]
        #在这里，要作一个增，删，编辑操作，以前台数据为准。
        #首先各取出前台与后台的ID数组
        fgIdArray = Array.new
        productsHashArray.each do |productHash|
          fgIdArray << productHash["id"].to_i
        end

        bgIdArray = Array.new
        openingStockDetails = openingStock.opening_stock_details
        openingStockDetails.each do |openingStockDetail|
          bgIdArray << openingStockDetail.id
        end

        idIntersectionArray = fgIdArray & bgIdArray
        addIdArray = fgIdArray - idIntersectionArray
        delIdArray = bgIdArray - idIntersectionArray
        OpeningStockDetail.delete(delIdArray)

        #在进行从新整理数据之前，先把采购订单的总金额置“0”
        openingStock.amount = 0
        openingStock.value_added_tax = 0
        openingStock.tax_amount = 0
        productsHashArray.each do |productHash|
          openingStockDetail = nil
          #只有当用户选择的产品不为空时，才有详细订单。
          if productHash["product_id"] !=""
            #没Id说明是新增加的。
            if productHash["id"] == ""
              openingStockDetail = OpeningStockDetail.new
            else
              openingStockDetail = OpeningStockDetail.find(productHash["id"].to_i)
            end
            openingStockDetail.product_id = productHash["product_id"]
            openingStockDetail.quantity = productHash["quantity"]
            #只有可以查看成本价权限的情况下，修改期初，所作的价格修改，才被保存。
            if session[:financial_management] == '是'
              openingStockDetail.unit_price = productHash["unit_price"]
              openingStockDetail.tax_price = productHash["tax_price"]
              openingStockDetail.tax_amount = productHash["tax_amount"]
              openingStockDetail.value_added_tax = productHash["value_added_tax"]
              openingStockDetail.amount = productHash["amount"]
            end
            openingStock.amount = openingStock.amount + openingStockDetail.amount #计算订单总金额
            openingStock.tax_amount = openingStock.tax_amount + openingStockDetail.tax_amount #计算订单总金额(含税)
            openingStock.value_added_tax = openingStock.value_added_tax + openingStockDetail.value_added_tax #计算订单总金额(含税)
            openingStockDetail.description = productHash["description"]
            openingStock.opening_stock_details << openingStockDetail
          end
        end
        openingStock.save!

        #把数据一个个的插入到结算表中。这里有个前提条件，就是不需要审批。
        if paramsHash['temporary'] != '1' && sysParam.audit_for_opening_stock_add == "否"
          #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
          ProductCollection.delete_all("resource_type = 'OpeningStock' AND resource_id = #{params[:opening_stock_id]}")

          openingStockDetails = openingStock.opening_stock_details
          openingStockDetails.each do |openingStockDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = openingStock.company_id
            productCollection.department_id = openingStock.department_id
            productCollection.employee_id = openingStock.employee_id
            productCollection.vendor_id = openingStock.vendor_id
            productCollection.warehouse_id = openingStock.warehouse_id
            productCollection.product_id = openingStockDetail.product_id
            productCollection.quantity =  openingStockDetail.quantity
            productCollection.amount = openingStockDetail.amount
            productCollection.tax_amount = openingStockDetail.tax_amount #计算订单总金额(含税)
            productCollection.value_added_tax = openingStockDetail.value_added_tax #税金
            productCollection.description =  openingStockDetail.description
            productCollection.action_date = openingStock.action_date
            productCollection.resource_id =  openingStock.id
            productCollection.resource_type =  OpeningStock.name
            productCollection.save!
          end
        end
      end

      info="成功"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info "ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end


  #更新审批状态
  def updateAuditingStatus
    begin
      openingStock = OpeningStock.find(params[:opening_stock_id])
      info = nil
      if openingStock !=nil
        OpeningStock.transaction do
          auditingStatus = params[:auditing_status]
          openingStock.auditor_id = session[:employee_id]
          openingStock.audit_opinion =  params[:audit_opinion]

          if(auditingStatus == "是")
            #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
            ProductCollection.delete_all("resource_type = 'OpeningStock' AND resource_id = #{params[:opening_stock_id]}")
            if openingStock.auditing_status == Constants::AUDIT_APPLY_ADD
              openingStock.auditing_status = Constants::PASS_APPLY_ADD
              openingStock.deal_with_status = ""
            elsif openingStock.auditing_status == Constants::AUDIT_APPLY_EDIT
              openingStock.auditing_status = Constants::PASS_APPLY_EDIT
              openingStock.deal_with_status = ""
            elsif openingStock.auditing_status == Constants::AUDIT_APPLY_CANCEL #申请撤消
              openingStock.auditing_status = Constants::PASS_APPLY_CANCEL
              openingStock.deal_with_status = Constants::CANCELED
            end
            openingStock.save!
            #记录变更历史
            openingStockHx = OpeningStockHx.new
            openingStockHx.opening_stock_id = openingStock.id
            openingStockHx.company_id = openingStock.company_id
            openingStockHx.department_id = openingStock.department_id
            openingStockHx.employee_id = openingStock.employee_id
            openingStockHx.vendor_id = openingStock.vendor_id
            openingStockHx.linkman = openingStock.linkman
            openingStockHx.phone = openingStock.phone
            openingStockHx.contract_number = openingStock.contract_number
            openingStockHx.tax_rate = openingStock.tax_rate
            openingStockHx.action_date = openingStock.action_date
            openingStockHx.description = openingStock.description
            openingStockHx.amount = openingStock.amount
            openingStockHx.tax_amount = openingStock.tax_amount #计算订单总金额(含税)
            openingStockHx.value_added_tax = openingStock.value_added_tax #税金
            openingStockHx.audit_opinion = openingStock.audit_opinion
            openingStockHx.auditor_id = openingStock.auditor_id

            #把数据一个个的插入到结算表中。只有状态为非撤销时,才进行此操作.
            if openingStock.auditing_status != Constants::PASS_APPLY_CANCEL
              openingStockDetails = openingStock.opening_stock_details
              openingStockDetails.each do |openingStockDetail|
                productCollection = ProductCollection.new
                productCollection.company_id = openingStock.company_id
                productCollection.department_id = openingStock.department_id
                productCollection.employee_id = openingStock.employee_id
                productCollection.vendor_id = openingStock.vendor_id
                productCollection.warehouse_id = openingStock.warehouse_id
                productCollection.product_id = openingStockDetail.product_id
                productCollection.quantity =  openingStockDetail.quantity
                productCollection.amount = openingStockDetail.amount
                productCollection.tax_amount = openingStockDetail.tax_amount #计算订单总金额(含税)
                productCollection.value_added_tax = openingStockDetail.value_added_tax #税金
                productCollection.description =  openingStockDetail.description
                productCollection.action_date = openingStock.action_date
                productCollection.resource_id =  openingStock.id
                productCollection.resource_type =  OpeningStock.name
                productCollection.save!

                #记录历史变更
                openingStockHxDetail = OpeningStockHxDetail.new
                openingStockHxDetail.product_id = openingStockDetail.product_id
                openingStockHxDetail.quantity =  openingStockDetail.quantity
                openingStockHxDetail.unit_price =  openingStockDetail.unit_price
                openingStockHxDetail.tax_price = openingStockDetail.tax_price
                openingStockHxDetail.tax_amount = openingStockDetail.tax_amount
                openingStockHxDetail.value_added_tax = openingStockDetail.value_added_tax
                openingStockHxDetail.amount =  openingStockDetail.amount
                openingStockHx.opening_stock_hx_details << openingStockHxDetail
              end
              openingStockHx.save!
            end
          else
            if openingStock.auditing_status == Constants::AUDIT_APPLY_ADD
              openingStock.auditing_status = Constants::REJECT_APPLY_ADD
            elsif openingStock.auditing_status == Constants::AUDIT_APPLY_EDIT
              openingStock.auditing_status = Constants::REJECT_APPLY_EDIT
            end
            openingStock.save!
          end

          #结算表处理完毕。
          info = "成功"
        end
      else
        info = "失败"
      end
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info "ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  def getOpeningStockDetailsById
    begin
      if session[:financial_management] == '是'
        selectStr = "is_locked,tax_price,discount,created_at,quantity,product_id,updated_at,opening_stock_id,lock_version,unit_price,tax_amount,id,value_added_tax,amount"
      else
        selectStr = "is_locked,discount,created_at,quantity,product_id,updated_at,opening_stock_id,lock_version,id"
      end
      openingStockDetails = OpeningStockDetail.find_all_by_opening_stock_id(params[:opening_stock_id],:select=>"#{selectStr}",:include=>[:product])
      jsonStr="{totalProperty:"+openingStockDetails.length.to_s+",root:"+openingStockDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec,:number,:unit]}})+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  def getOpeningStockById
    begin
      openingStock = OpeningStock.find(params[:id])
      rootStr = openingStock.to_json(:include=>{:vendor=>{:only=>[:id,:name]},:warehouse=>{:only=>[:id,:name]}})
      jsonStr = "{root:["+rootStr+"]}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #申请撤消
  def applyToCancel
    begin
      openingStock = OpeningStock.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_opening_stock_cancel == "否"
        openingStock.auditing_status = Constants::PASS_APPLY_CANCEL
        openingStock.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'OpeningStock' AND resource_id = #{params[:id]}")
        #如果不需要审核，则把汇总表中的数据设置为is_locked = 1
      else
        openingStock.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      openingStock.auditor_id = session[:employee_id]
      openingStock.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到变更历史的摘要
  def getHxesById
    openingStockHxes = OpeningStockHx.find_all_by_opening_stock_id(params[:id],:include=>[:department,:employee,:warehouse])
    jsonStr="{totalProperty:"+openingStockHxes.length.to_s+",root:"+openingStockHxes.to_json(:include=>[:department,:employee,:warehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据变更Id得到详细信息
  def getHxDetailsByHxId
    openingStockHxDetails = OpeningStockHxDetail.find_all_by_opening_stock_hx_id(params[:id],:include=>[:product])
    jsonStr="{totalProperty:"+openingStockHxDetails.length.to_s+",root:"+openingStockHxDetails.to_json(:include=>[:product])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #为通用报表提供数据
  def getOpeningInfoForCommonReport
    begin
      #begin
      conditionsStr = ''

      #处于申请或已撤消状态的订单，不计算在内。
      if conditionsStr == ''
        conditionsStr = " os.auditing_status not like '%#{Constants::APPLY}%' AND os.auditing_status not like '%#{Constants::PASS_APPLY_CANCEL}%' "
      else
        conditionsStr = conditionsStr + " AND os.auditing_status not like '%#{Constants::APPLY}%' AND os.auditing_status not like '%#{Constants::PASS_APPLY_CANCEL}%' "
      end

      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " os.vendor_id = #{params[:vendor_id]}"
        else
          conditionsStr = conditionsStr + " AND os.vendor_id = #{params[:vendor_id]}"
        end
      end

      if params[:warehouse_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " os.warehouse_id = #{params[:warehouse_id]}"
        else
          conditionsStr = conditionsStr + " AND os.warehouse_id = #{params[:warehouse_id]}"
        end
      end

      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " od.product_id = '#{params[:product_id]}'"
        else
          conditionsStr = conditionsStr+" AND od.product_id = '#{params[:product_id]}'"
        end
      end

      if conditionsStr != ""
        conditionsStr = " where " + conditionsStr
      end

      if session[:financial_management] == '是'
        selectStr = "p.name product_name,p.number product_number,od.unit_price,od.tax_price,sum(od.quantity) quantity,sum(od.amount) amount,sum(od.value_added_tax) value_added_tax,sum(od.tax_amount) tax_amount"
      else
        selectStr = "p.name product_name,p.number product_number,sum(od.quantity) quantity"
      end
      groupByStr = " group by od.product_id"
      if params[:vendor_id].to_s == ""
        if params[:vendor_group].to_s == 'true'
          groupByStr = groupByStr + ",os.vendor_id"
          selectStr = selectStr + ",v.name vendor_name"
        end
      end

      if params[:warehouse_id].to_s == ""
        if params[:warehouse_group].to_s == 'true'
          groupByStr = groupByStr + ",os.warehouse_id"
          selectStr = selectStr + ",w.name warehouse_name"
        end
      end

      #记录总记录数量
      openingStocksTotal = OpeningStock.select("os.id,od.amount").joins("os
                        left join opening_stock_details od on os.id = od.opening_stock_id
                        left join products p on od.product_id = p.id
                        left join warehouses w on w.id = os.warehouse_id
                        left join vendors v on v.id = os.vendor_id " + conditionsStr + groupByStr).order("os.id")

      openingStocksTotalAmount = OpeningStock.select("os.id,sum(od.amount) amount,sum(od.value_added_tax) value_added_tax,sum(od.tax_amount) tax_amount").joins("os
                        left join opening_stock_details od on os.id = od.opening_stock_id
                        left join products p on od.product_id = p.id
                        left join warehouses w on w.id = os.warehouse_id
                        left join vendors v on v.id = os.vendor_id " + conditionsStr).order("os.id").first

      openingStocks = OpeningStock.select(selectStr).joins("os
                        left join opening_stock_details od on os.id = od.opening_stock_id
                        left join products p on od.product_id = p.id
                        left join warehouses w on w.id = os.warehouse_id
                        left join vendors v on v.id = os.vendor_id " + conditionsStr + groupByStr,).offset(params[:start].to_i).limit(params[:limit].to_i).order("os.id")

      #此语句主要用来求总金额与损益金额
      amountTotal = 0

      if openingStocksTotalAmount != nil && session[:financial_management] == '是'
        amountTotal = openingStocksTotalAmount.amount.to_f
        valueAddedTaxTotal = openingStocksTotalAmount.value_added_tax.to_f
        taxAmountTotal = openingStocksTotalAmount.tax_amount.to_f
      else
        amountTotal = 0
        valueAddedTaxTotal = 0
        taxAmountTotal = 0
      end

      logger.info amountTotal
      jsonStr="{totalProperty:"+openingStocksTotal.length.to_s+",amount:#{amountTotal.to_s},value_added_tax:#{valueAddedTaxTotal.to_s},tax_amount:#{taxAmountTotal.to_s},root:"+openingStocks.to_json()+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end
end
